package org.mspring.platform.dao.query.criterion;

import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.mspring.platform.dao.query.QueryBuilder;
import org.mspring.platform.dao.query.QueryHelper;
import org.mspring.platform.dao.query.convert.Converter;
import org.mspring.platform.dao.query.convert.ConverterManager;

/**
 *
 * @author Gao Youbo
 * @since Jan 31, 2012
 */
public class SimpleExpression implements Criterion {

    private static final long serialVersionUID = -4391378598945434436L;
    protected String hqlName;
    protected String paramKey;
    protected Object paramValue;
    protected String operation;
    protected Class<?> paramClass;

    protected SimpleExpression(String hqlName, String paramKey, String operation, Class<?> paramClass) {
        this.hqlName = hqlName;
        this.paramKey = paramKey;
        this.operation = operation;
        this.paramClass = paramClass;
    }

    protected SimpleExpression(String hqlName, Object paramValue, String operation) {
        this.hqlName = hqlName;
        this.paramValue = paramValue;
        this.operation = operation;
    }

    @Override
    public String toHqlString(QueryBuilder builder) {
        if (paramValue != null) { // 如果设置了参数值
            setParams(builder, paramValue);
            return new StringBuilder().append(hqlName).append(operation).append(":").append(valuedQualifyHql(hqlName)).toString();
        } else {
            Map<String, Object> queryParams = builder.getQueryParams();
            String value = MapUtils.getString(queryParams, paramKey);
            if (value == null) { // 没有设置参数值，那么需要从queryParams中获取
                return null;
            }
            setParams(builder, value, paramClass);
            return new StringBuilder().append(hqlName).append(operation).append(":").append(QueryHelper.qualifyHql(hqlName)).toString();
        }
    }

    protected void setParams(QueryBuilder builder, String value, Class<?> paramClass) {
        Converter converter = ConverterManager.lookup(paramClass);
        builder.getNamedQueryParams().put(QueryHelper.qualifyHql(hqlName), converter.convert(paramClass, value));
        builder.getValidQueryParams().put(paramKey, value);
    }

    protected void setParams(QueryBuilder builder, Object value) {
        String paramName = valuedQualifyHql(hqlName);
        builder.getNamedQueryParams().put(paramName, value);
        builder.getValidQueryParams().put(paramName, value);
    }

    protected String valuedQualifyHql(String hqlName) {
        return QueryHelper.qualifyHql(hqlName, "valued_");
    }

}
